﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenRasta.Pipeline;
using OpenRasta.Web;
using uREST.Core.Extensions;

namespace uREST.Core.Contributors
{
    public class LegacyHttpProtocolContributor : IPipelineContributor
    {
        public void Initialize(IPipeline pipelineRunner)
        {
            pipelineRunner
                .Notify(OverrideStatus)
                .After<KnownStages.IOperationExecution>()
                .And.Before<KnownStages.IOperationResultInvocation>();
        }

        protected PipelineContinuation OverrideStatus(ICommunicationContext context)
        {
            if (context.Request.Headers["X-HTTP-Protocol-Support"] != null &&
                context.Request.Headers["X-HTTP-Protocol-Support"].ToLower() == "legacy")
            {
                var currentStatusCode = context.OperationResult.StatusCode;
                context.Response.Headers.Add("X-HTTP-Status-Code", currentStatusCode.ToString());
                context.OperationResult = new OperationResult.OK
                {
                    ResponseResource = context.OperationResult.ResponseResource
                };
            }

            return PipelineContinuation.Continue;
        }
    }
}
